const Koa = require('koa');
const render = require("@koa/ejs");
const { koaBody } = require('koa-body');
const path = require("path");
const webpush = require('web-push');
const vapidKeys = {
	publicKey:
	  'BGRN5ITrPDx_IVkqBNqk4unNPKXW0r_FEtDsdKxpAhCNJN2uA_0j79D52B4xQyIVPTW4p35qUoYSjBuAix4Ccng',
	privateKey: 'hbCKYcq9xDralYSGPMJWuipmp4KfipxQvMgBDlZHeuQ',
};
webpush.setVapidDetails(
	'mailto:gyw12345678@foxmail.com',
	vapidKeys.publicKey,
	vapidKeys.privateKey,
);
const app = new Koa();
const Router = require('@koa/router');
render(app, {
	root: path.join(__dirname, 'views'),
	layout: 'template',
	viewExt: 'ejs',
	cache: false,
	debug: true,
})

const router = new Router();
const userList = [];
app
	.use(koaBody())
	.use(router.routes())
	.use(router.allowedMethods());
	
router.all('/', async (ctx) => {
	await ctx.render('index');
})
router.post('/upload', async (ctx) => {
	console.log(ctx.request.body);
	console.log(JSON.parse(ctx.request.body.userInfo));
	webpush.sendNotification(JSON.parse(ctx.request.body.userInfo), JSON.stringify({
		title: ctx.request.body.title,
		body: ctx.request.body.body,
		url: ctx.request.body.url
	}), {
		proxy: 'http://127.0.0.1:1087'
	}).then(res => {
		console.log(res);
	}).catch(e => {
		console.log(e);
	})
	ctx.body = 'send success';
})
app.listen(7000);



// const pushSubscription = {"endpoint":"https://wns2-sg2p.notify.windows.com/w/?token=BQYAAADH%2fPYgCAkoRYfQWk57KNOz%2bPrCBaOzVmSkZlYJHpsIpr8HIWKFQHDwsluFwIS7P8F6cuTO0Y%2bAa4moUg%2fsRBzWbBLz59gkFD2%2bhq3Dm0bIxgnLMBCgJW8ZvqviwjdQ%2bc4h%2frs9psSU%2bM6XQVrvDt93hbSLqDRT3woXd7A4JAAp%2f%2bzBqu5wVnIobtzKYRCXNtlnPDpQpcgJ5z8PeleB86fdULepgPXFG6IOzp8kAONUGSIY6MEjZNyAt0ohO9y60YpwqGcJJ%2bdhym3bktOoy6jbt2jKk3Y5XewBAD9%2bk5WKR86cdUkraWrUJjGQHS9g8HI%3d","expirationTime":null,"keys":{"p256dh":"BPcZkU_nBpWrX5dx6InLsonU_Fl-c24Ld1FzYC6DEiwSN5eGQvduf8tUZpY3Hq69-5YVilDwETMImb0Bf7dcBg8","auth":"7-mFI5FbaY7rjgpf3qj0ZQ"}}
// webpush.sendNotification(pushSubscription, JSON.stringify({
// 	title: '标题标题标题',
// 	body: '22222222222',
// 	url: 'https://cast.flashget.com'
// }));